package com.wac.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wac.blog.pojo.Blog;
import com.wac.blog.pojo.Comment;
import com.wac.blog.pojo.Question;
import com.wac.blog.pojo.UserInfo;
import com.wac.blog.service.BlogService;
import com.wac.blog.service.CommentService;
import com.wac.blog.service.QuestionService;
import com.wac.blog.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wac
 * @since 2020-08-04
 */
@Controller
@RequestMapping("/userinfo")
public class UserInfoController {
    @Autowired
    UserInfoService userInfoService;

    @Autowired
    BlogService blogService;

    @Autowired
    CommentService commentService;

    @Autowired
    QuestionService questionService;

    @RequestMapping("/setting/{uid}")
    public String list(@PathVariable String uid, Model model){
        UserInfoCallBack(uid,model );
        UserInfo userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("uid", uid));
        model.addAttribute("userInfo",userInfo );
        return "user/settings";
    }

    @RequestMapping("/update/{uid}")
    public String update(@PathVariable String uid,UserInfo userInfo){
        userInfo.setUid(uid);
        userInfoService.updateById(userInfo);
        return "redirect:/userinfo/setting/"+uid;
    }

    private void UserInfoCallBack(String uid,Model model){
        UserInfo userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("uid", uid));
        model.addAttribute("userInfo",userInfo );
        if (userInfo.getHobby()!=null && !userInfo.getHobby().equals("")) {
            String[] hobbies = userInfo.getHobby().split(",");
            model.addAttribute("hobbies", hobbies);
        }
        int blogCount = blogService.count(new QueryWrapper<Blog>().eq("author_id", uid));
        int questionCount = questionService.count(new QueryWrapper<Question>().eq("author_id", uid));
        int commentCount = commentService.count(new QueryWrapper<Comment>().eq("user_id", uid));
        model.addAttribute("blogCount", blogCount);
        model.addAttribute("questionCount",questionCount );
        model.addAttribute("commentCount",commentCount );
    }
}

